﻿using LiaoChengFei.Core;
using Microsoft.EntityFrameworkCore;
using System.Linq;

namespace LiaoChengFei.DoMain
{
    public class EfRepository<TEntity> : IRepository<TEntity> where TEntity : class
    {
        private LiaoChengFeiDbContext _liaoChengFeiDbContext;

        public EfRepository(LiaoChengFeiDbContext  liaoChengFeiDbContext)
        {
            this._liaoChengFeiDbContext = liaoChengFeiDbContext;
        }

        public DbContext DbContext
        {
            get
            {
                return _liaoChengFeiDbContext;
            }
        }

        /// <summary>
        /// 
        /// </summary>
        public DbSet<TEntity> Entities
        {
            get
            {
                return _liaoChengFeiDbContext.Set<TEntity>();
            }
        }

        /// <summary>
        /// 
        /// </summary>
        public IQueryable<TEntity> Table
        {
            get
            {
                return Entities;
            }
        }

        public void Delete(TEntity entity, bool isSave = true)
        {
            Entities.Remove(entity);
            if (isSave)
                _liaoChengFeiDbContext.SaveChanges();
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public TEntity GetById(object id)
        {
            return _liaoChengFeiDbContext.Set<TEntity>().Find(id);
        }

        public void Insert(TEntity entity, bool isSave = true)
        {
            Entities.Add(entity);
            if (isSave)
                _liaoChengFeiDbContext.SaveChanges();
        }

        public void Update(TEntity entity, bool isSave = true)
        {
            if (isSave)
                _liaoChengFeiDbContext.SaveChanges();
        }
    }
}
